package com.my.bookstore.dao.impl;

import com.my.bookstore.dao.BookDAO;
import com.my.bookstore.domain.Book;
import com.my.bookstore.domain.ShoppingCartItem;
import com.my.bookstore.web.CriteriaBook;
import com.my.bookstore.web.Page;

import java.util.Collection;
import java.util.List;

/**
 * Created by YJH on 2017/7/17 22:58.
 */
public class BookDAOImpl extends BaseDAO<Book> implements BookDAO {


    /**
     * 根据id查询
     */
    @Override
    public Book getBook(int id) {
        String sql = "SELECT mybooks.id AS id, mybooks.Author AS author, mybooks.Title AS title, mybooks.Price AS price, mybooks.Publishingdate AS publishingDate, mybooks.Salesamount AS salesAmount, mybooks.Storenumber AS storeNumber, mybooks.Remark AS remark FROM mybooks WHERE mybooks.Id = ?";
        return query(sql, id);
    }

    @Override
    public Page<Book> getPage(CriteriaBook cb) {
        Page page = new Page<>(cb.getPageNo());
        page.setTotalItemNum(getTotalBookNumber(cb));
        //校验PageNo的合法性
        cb.setPageNo(page.getPageNo());
        page.setList(getPageList(cb, 3));
        return page;
    }

    @Override
    public long getTotalBookNumber(CriteriaBook cb) {
        String sql = "SELECT count(id) FROM mybooks WHERE mybooks.Price >= ? AND mybooks.Price <= ?";
        return getSingleVal(sql, cb.getMinPrice(), cb.getMaxPrice());
    }

    /**
     * 分页查询
     */
    @Override
    public List<Book> getPageList(CriteriaBook cb, int pageSize) {
        String sql = "SELECT " +
                "mybooks.id AS id, " +
                "mybooks.Author AS author, " +
                "mybooks.Title AS title, " +
                "mybooks.Price AS price, " +
                "mybooks.Publishingdate AS publishingDate, " +
                "mybooks.Salesamount AS salesAmount, " +
                "mybooks.Storenumber AS storeNumber, " +
                "mybooks.Remark AS remark " +
                "FROM mybooks " +
                "WHERE " +
                "mybooks.Price >= ? AND mybooks.Price <= ? LIMIT ?, ?";

        return queryForList(sql, cb.getMinPrice(), cb.getMaxPrice(), (cb.getPageNo() - 1) * pageSize, pageSize);
    }

    @Override
    public int getStoreNumber(Integer id) {
        String sql = "SELECT mybooks.Storenumber FROM mybooks WHERE mybooks.Id = ?";
        return getSingleVal(sql, id);
    }

    @Override
    public void batchUpdateStoreNumberAndSalesAmount(Collection<ShoppingCartItem> items) {

    }
}
